package org.hy.corn_task.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import okhttp3.*;

import javax.net.ssl.*;
import java.io.IOException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

public class ResRequestUtil {

    /**
     * 发起请求
     * @return
     */
    public static JSONObject doPostRequest(Request request) throws IOException {
        OkHttpClient httpClinet = getHttpClinet();
//        Request request = buildPostRequest(url,header,requestBodyody);

        Response execute = httpClinet.newCall(request).execute();
        ResponseBody responseBody = execute.body();
        assert responseBody != null;
        String resBody = responseBody.string();
        JSONObject jsonBody = JSONUtil.parseObj(resBody);
        return jsonBody;

    }

    public static Request buildGetRequest(String url, Headers header, RequestBody requestBodyody){
        return new Request.Builder()
                .url(url)
                .headers(header)
                .get()
                .build();
    }

    /**
     * 创建post请求
     * @param url
     * @param header
     * @param requestBodyody
     * @return
     */
    public static Request buildPostRequest(String url, Headers header, RequestBody requestBodyody){
        return new Request.Builder()
                .url(url)
                .headers(header)
                .post(requestBodyody)
                .build();
    }


    /**
     * 创建客户端
     * @return
     */
    public static OkHttpClient getHttpClinet(){
        return new OkHttpClient().newBuilder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60,TimeUnit.SECONDS)
                .sslSocketFactory(getSSLSocketFactory(), getX509TrustManager()).build();
    }

    //忽略https证书
    public static SSLSocketFactory getSSLSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }

        return trustManager;
    }
    public static TrustManager[] getTrustManager() {
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
        return trustAllCerts;
    }

}
